package com.stars.easyms.base.http;

import com.alibaba.fastjson.JSON;
import com.stars.easyms.base.annotation.CustomToString4Log;
import com.stars.easyms.base.constant.RestCodeConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>className: EasyMsResponseEntity</p>
 * <p>description: 返回消息体</p>
 *
 * @author guoguifang
 * @version 1.6.1
 * @date 2020/8/17 20:13
 */
public class EasyMsResponseEntity<T> {

    private Header header = new Header();

    private T body;

    public boolean isSuccess() {
        return RestCodeConstants.DEFAULT_SUCC_CODE.equals(getRetCode());
    }

    public T getBody() {
        return this.body;
    }

    public void setBody(T body) {
        this.body = body;
    }

    public String getRetCode() {
        return this.header.retCode;
    }

    public void setRetCode(String retCode) {
        this.header.retCode = retCode;
    }

    public String getRetMsg() {
        return this.header.retMsg;
    }

    public void setRetMsg(String retMsg) {
        this.header.retMsg = retMsg;
    }

    public String getErrorDesc() {
        return this.header.errorDesc;
    }

    public void setErrorDesc(String errorDesc) {
        this.header.errorDesc = errorDesc;
    }

    public Map<String, Object> toMap() {
        Map<String, Object> objectMap = new HashMap<>(8);
        objectMap.put("success", isSuccess());
        objectMap.put("retCode", getRetCode());
        objectMap.put("retMsg", getRetMsg());
        objectMap.put("errorDesc", getErrorDesc());
        objectMap.put("body", getBody());
        return objectMap;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{\"success\":")
                .append(isSuccess())
                .append(",\"retCode\":\"")
                .append(getRetCode())
                .append("\"");

        String retMsg = getRetMsg();
        if (StringUtils.isNotBlank(retMsg)) {
            stringBuilder.append(",\"retMsg\":\"")
                    .append(retMsg)
                    .append("\"");
        }

        String errorDesc = getErrorDesc();
        if (StringUtils.isNotBlank(errorDesc)) {
            stringBuilder.append(",\"errorDesc\":\"")
                    .append(errorDesc)
                    .append("\"");
        }

        if (body != null) {
            stringBuilder.append(",\"body\":");
            if (body.getClass().isAnnotationPresent(CustomToString4Log.class)) {
                stringBuilder.append(body.toString());
            } else {
                stringBuilder.append(JSON.toJSONString(body));
            }
        }

        return stringBuilder.append("}").toString();
    }

    private static class Header {

        String retCode;

        String retMsg;

        String errorDesc;

        private Header() {
            this.retCode = "0000";
        }
    }
}
